package com.yuhong.springbootinit.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.yuhong.springbootinit.constant.CommonConstant;
import com.yuhong.springbootinit.service.ApplicantService;
import com.yuhong.springbootinit.mapper.ApplicantMapper;
import com.yuhong.springbootinit.model.dto.analysis.ApplicantBgResponse;
import com.yuhong.springbootinit.model.dto.analysis.ApplicantMajorResponse;
import com.yuhong.springbootinit.model.dto.applicant.ApplicantQueryRequest;
import com.yuhong.springbootinit.model.entity.Applicant;
import com.yuhong.springbootinit.model.vo.ApplicantVO;
import com.yuhong.springbootinit.utils.SqlUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
* @author 10467
* @description 针对表【user】的数据库操作Service实现
* @createDate 2025-02-22 13:52:10
*/
@Service
public class ApplicantServiceImpl extends ServiceImpl<ApplicantMapper, Applicant>
    implements ApplicantService {


    @Resource
    private ApplicantMapper applicantMapper;

    @Override
    public Page<ApplicantVO> getApplicantVOPage(Page<Applicant> applicantPage) {

        List<Applicant> applicantList = applicantPage.getRecords();
        Page<ApplicantVO> applicantVOPage = new Page<>(applicantPage.getCurrent(), applicantPage.getSize(), applicantPage.getTotal());
        if (CollUtil.isEmpty(applicantList)) {
            return applicantVOPage;
        }

        List<ApplicantVO> applicantVOS = BeanUtil.copyToList(applicantList, ApplicantVO.class);
        applicantVOPage.setRecords(applicantVOS);

//        // 1. 关联查询用户信息
//        Set<Long> userIdSet = postList.stream().map(Application::getUserId).collect(Collectors.toSet());
//        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
//                .collect(Collectors.groupingBy(User::getId));
//        // 2. 已登录，获取用户点赞、收藏状态
//        Map<Long, Boolean> postIdHasThumbMap = new HashMap<>();
//        Map<Long, Boolean> postIdHasFavourMap = new HashMap<>();
//        User loginUser = userService.getLoginUserPermitNull(request);
//        if (loginUser != null) {
//            Set<Long> postIdSet = postList.stream().map(Post::getId).collect(Collectors.toSet());
//            loginUser = userService.getLoginUser(request);
//            // 获取点赞
//            QueryWrapper<PostThumb> postThumbQueryWrapper = new QueryWrapper<>();
//            postThumbQueryWrapper.in("postId", postIdSet);
//            postThumbQueryWrapper.eq("userId", loginUser.getId());
//            List<PostThumb> postPostThumbList = postThumbMapper.selectList(postThumbQueryWrapper);
//            postPostThumbList.forEach(postPostThumb -> postIdHasThumbMap.put(postPostThumb.getPostId(), true));
//            // 获取收藏
//            QueryWrapper<PostFavour> postFavourQueryWrapper = new QueryWrapper<>();
//            postFavourQueryWrapper.in("postId", postIdSet);
//            postFavourQueryWrapper.eq("userId", loginUser.getId());
//            List<PostFavour> postFavourList = postFavourMapper.selectList(postFavourQueryWrapper);
//            postFavourList.forEach(postFavour -> postIdHasFavourMap.put(postFavour.getPostId(), true));
//        }
        // 填充信息
//        List<PostVO> postVOList = postList.stream().map(post -> {
//            PostVO postVO = PostVO.objToVo(post);
//            Long userId = post.getUserId();
//            User user = null;
//            if (userIdUserListMap.containsKey(userId)) {
//                user = userIdUserListMap.get(userId).get(0);
//            }
//            postVO.setUser(userService.getUserVO(user));
//            postVO.setHasThumb(postIdHasThumbMap.getOrDefault(post.getId(), false));
//            postVO.setHasFavour(postIdHasFavourMap.getOrDefault(post.getId(), false));
//            return postVO;
//        }).collect(Collectors.toList());
//        postVOPage.setRecords(postVOList);
        return applicantVOPage;
    }

    @Override
    public ApplicantVO getApplicantVO(Applicant applicant, HttpServletRequest request) throws JsonProcessingException {

        ApplicantVO applicantVO = new ApplicantVO();
        BeanUtil.copyProperties(applicantVO, applicant);

        return applicantVO;
    }

    @Override
    public QueryWrapper<Applicant> getQueryWrapper(ApplicantQueryRequest applicantQueryRequest) {
        QueryWrapper<Applicant> queryWrapper = new QueryWrapper<>();
        if (applicantQueryRequest == null) {
            return queryWrapper;
        }

        Integer age = applicantQueryRequest.getAge();
        Integer sex = applicantQueryRequest.getSex();
        Integer rank = applicantQueryRequest.getRank();
        String major = applicantQueryRequest.getMajor();
        String sortField = applicantQueryRequest.getSortField();
        String sortOrder = applicantQueryRequest.getSortOrder();


        // 拼接查询条件
        queryWrapper.eq(ObjectUtils.isNotEmpty(age), "age", age);
        queryWrapper.eq(ObjectUtils.isNotEmpty(sex), "sex", sex);
        queryWrapper.eq(ObjectUtils.isNotEmpty(rank), "rank", rank);

        queryWrapper.eq(ObjectUtils.isNotEmpty(major), "major", major);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    @Override
    public ApplicantBgResponse getApplicantBgRatio() {

        QueryWrapper<Applicant> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("bg", "COUNT(*) as count").groupBy("bg");
        List<Map<String, Object>> bgCounts = applicantMapper.selectMaps(queryWrapper);

        // 计算总职位数
        int totalApplicants = bgCounts.stream()
                .mapToInt(map -> Integer.parseInt(map.get("count").toString()))
                .sum();

        ApplicantBgResponse applicantBgResponse = new ApplicantBgResponse();

        // 创建结果列表
//        List<applicantSalaryRatioDTO> ratios = new ArrayList<>();
//        for (Map<String, Object> map : salaryCounts) {
//            applicantSalaryRatioDTO dto = new applicantSalaryRatioDTO();
//            dto.setSalary(Integer.parseInt(map.get("salary").toString()));
//
//            int count = Integer.parseInt(map.get("count").toString());
//            double ratio = totalapplicants > 0 ? ((double) count / totalapplicants) : 0;
//            dto.setRate(ratio);
//            ratios.add(dto);
//        }

        applicantBgResponse.setDataList(bgCounts);
        applicantBgResponse.setTotal(totalApplicants);
        applicantBgResponse.setPostNum(bgCounts.size());

        return applicantBgResponse;
    }

    @Override
    public ApplicantMajorResponse getApplicantMajorRatio() {

        QueryWrapper<Applicant> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("major", "COUNT(*) as count").groupBy("major");
        List<Map<String, Object>> majorCounts = applicantMapper.selectMaps(queryWrapper);

        // 计算总职位数
        int totalApplicants = majorCounts.stream()
                .mapToInt(map -> Integer.parseInt(map.get("count").toString()))
                .sum();

        ApplicantMajorResponse applicantMajorResponse = new ApplicantMajorResponse();

        // 创建结果列表
//        List<applicantSalaryRatioDTO> ratios = new ArrayList<>();
//        for (Map<String, Object> map : salaryCounts) {
//            applicantSalaryRatioDTO dto = new applicantSalaryRatioDTO();
//            dto.setSalary(Integer.parseInt(map.get("salary").toString()));
//
//            int count = Integer.parseInt(map.get("count").toString());
//            double ratio = totalapplicants > 0 ? ((double) count / totalapplicants) : 0;
//            dto.setRate(ratio);
//            ratios.add(dto);
//        }

        applicantMajorResponse.setDataList(majorCounts);
        applicantMajorResponse.setTotal(totalApplicants);
        applicantMajorResponse.setPostNum(majorCounts.size());

        return applicantMajorResponse;

    }
}




